import 'dart:convert';
import 'dart:typed_data';

import 'package:camera/camera.dart';
import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/utils/user_manager.dart';
import 'package:enterprise_v6_app/app/modules/auth/face/iface.dart';
import 'package:enterprise_v6_app/app/modules/auth/face/model.dart';

class FaceAuthController extends GetxController {
  FaceAuthStatus? status;

  final personId = UserManager.getUserId();

  /// 最大三次
  int _tryTimes = 0;

  Uint8List? image;

  CameraController? camera;

  bool? suc;

  Future<void> initCamera() async {
    final cameras = await availableCameras();
    final frontCamera = cameras
        .where(
          (e) => e.lensDirection == CameraLensDirection.front,
        )
        .firstOrNull;
    if (frontCamera == null) {
      AppToast.showWarning('无前置摄像头');
      Get.back(result: false);
      return;
    }
    camera = CameraController(frontCamera, ResolutionPreset.medium, enableAudio: false);
    await camera?.initialize();
    update();
  }

  @override
  void onReady() {
    super.onReady();
    initCamera();
    refreshPerm();
    if (personId == null) {
      AppToast.showWarning('无人员ID');
      Get.back(result: false);
    }
  }

  @override
  void onClose() {
    camera?.dispose();
    super.onClose();
  }

  Future<void> startAuth() async {
    if (status == FaceAuthStatus.noPerm) {
      return;
    }
    if (_tryTimes > 99) {
      Get.back(result: false);
      AppToast.showWarning('已达到最大次数，请重新进入');
      return;
    }
    _tryTimes++;
    status = FaceAuthStatus.ing;
    update();
    if (image == null) {
      await capture();
    }
    suc = await FaceAuthApi.recog(base64Encode(image!));
    if (suc ?? false) {
      status = FaceAuthStatus.success;
    } else {
      status = FaceAuthStatus.failed;
    }
    update();
  }

  Future<void> refreshPerm() async {
    final have = await haveCameraPerm;
    if (have) {
      status = FaceAuthStatus.before;
    } else {
      status = FaceAuthStatus.noPerm;
    }
    update();
  }

  /// Just a mock
  Future<bool> get haveCameraPerm async {
    await Future.delayed(const Duration(milliseconds: 177));
    return Future.value(true);
  }

  Future<void> capture() async {
    final file = await camera?.takePicture();
    if (file != null) {
      image = await file.readAsBytes();
      status = FaceAuthStatus.ing;
      update();
    }
  }
}
